namespace EyeOpen.SampleCms.Web.UI.Controls
{
    using System;
    using System.Security;
    using System.Web;
    using System.Web.UI.WebControls;
    using EyeOpen.SampleCms.Web.Contents;

    public partial class ContentManager : BaseUserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                if (!IsPostBack)
                {
                    BindContents();
                }
                
                return;
            }

            ((Literal)LoginView1.FindControl("ltlBody")).Text = SectionContents.CurrentSectionContent.Body;
        }

        protected void SaveClick(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                throw new SecurityException("You must be a logged user to save contents");
            }

            SectionContents.CurrentSectionContent.Title = ((TextBox)LoginView1.FindControl("txtTitle")).Text;
            SectionContents.CurrentSectionContent.Description = ((TextBox)LoginView1.FindControl("txtDescription")).Text;
            SectionContents.CurrentSectionContent.Keywords = ((TextBox)LoginView1.FindControl("txtKeywords")).Text;
            SectionContents.CurrentSectionContent.Body = ((TextBox)LoginView1.FindControl("txtBody")).Text;
            SectionContents.CurrentSectionContent.Url = VirtualPathUtility.ToAppRelative(HttpContext.Current.Request.Path);
            SectionContents.CurrentSectionContent.PagePath = ((DropDownList)LoginView1.FindControl("ddlPages")).SelectedValue;
            SectionContents.Save();
        }

        private void BindContents()
        {
            var ddlPages = (DropDownList)LoginView1.FindControl("ddlPages");
            ddlPages.DataSource = ConfigurationWrapper.Pages;
            ddlPages.DataBind();

            var pagePath = ddlPages.Items.FindByValue(SectionContents.CurrentSectionContent.PagePath);
            var position = ddlPages.Items.IndexOf(pagePath);
            if (position >= 0)
            {
                ddlPages.SelectedIndex = position;
            }

            ((TextBox)LoginView1.FindControl("txtTitle")).Text = SectionContents.CurrentSectionContent.Title;
            ((TextBox)LoginView1.FindControl("txtDescription")).Text = SectionContents.CurrentSectionContent.Description;
            ((TextBox)LoginView1.FindControl("txtKeywords")).Text = SectionContents.CurrentSectionContent.Keywords;
            ((TextBox)LoginView1.FindControl("txtBody")).Text = SectionContents.CurrentSectionContent.Body;
        }
    }
}